package frontend;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Dog;
import model.DogValidator;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import db.DogDAO;

/**
 * Servlet implementation class DogServlet
 */
@WebServlet("/s")
public class DogServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    Logger logger = Logger.getLogger(DogServlet.class);

    /**
     * @see HttpServlet#HttpServlet()
     */
    public DogServlet() {
	super();
	PropertyConfigurator.configure("log4j.properties");
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
	    HttpServletResponse response) throws ServletException, IOException {
	DogDAO dogDAO = new DogDAO();
	if (request.getParameter("id") != null) {
	    try {
		RequestDispatcher view = request.getRequestDispatcher("/dog.jsp");
		if(request.getAttribute("errors") == null){
		    	Integer dogNr = new Integer(request.getParameter("id"));
			Dog dog = dogDAO.findById(dogNr);
			if(dog == null){
			    logger.error("No dog with id "+dogNr);
			    throw new  RuntimeException();
			}
			DogForm dogForm = convertToDogForm(dog);
			request.setAttribute("dog", dogForm);	
			logger.debug("Get dog with id "+dogNr);
		}
		view.forward(request, response);
	    } catch (Exception e) {
		RequestDispatcher view = request.getRequestDispatcher("/error.jsp");
		request.setAttribute("err", "VIGA! Sellise identifikaatoriga koera ei eksisteeri!");
		view.forward(request, response);
	    }
	} else {
	    logger.debug("Returning all dogs");
	    RequestDispatcher view = request.getRequestDispatcher("/dogs.jsp");	    
	    List<Dog> dogs = dogDAO.findAll();
	    request.setAttribute("dogs", dogs);
	    view.forward(request, response);
	}
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
	    HttpServletResponse response) throws ServletException, IOException {
	DogForm dogData = getDogFormFromRequest(request);
	Map<String, String> errors = DogValidator.validateDog(dogData);
	if(errors.size() > 0){
	    logger.info("Invalid data");
	    request.setAttribute("errors", errors);
	    request.setAttribute("dog", dogData);
	    request.setAttribute("hasError", true);
	    doGet(request, response);
	    return;
	}else{
	    DogDAO dao = new DogDAO();
	    dao.update(dogData.convertToDog());
	    logger.debug("Update dog "+ dogData.getId()+" data");
	}
	response.sendRedirect("/dog/s?id="+request.getParameter("id"));
    }
    
    private DogForm getDogFormFromRequest(HttpServletRequest request){
	DogForm dogForm = new DogForm();
	dogForm.setName(request.getParameter("name"));
	dogForm.setAge(request.getParameter("age"));
	dogForm.setBreed(request.getParameter("breed"));
	dogForm.setId(request.getParameter("id"));
	dogForm.setDescription(request.getParameter("description"));
	return dogForm;
    }
    
    private DogForm convertToDogForm(Dog dog){
	if(dog == null){
	    return null;
	}
	DogForm dogForm = new DogForm();
	dogForm.setName(dog.getName());
	dogForm.setAge(dog.getAgeInMonths() != null ? dog.getAgeInMonths().toString():null);
	dogForm.setBreed(dog.getBreed());
	dogForm.setId(dog.getDogNr() != null?dog.getDogNr().toString():null);
	dogForm.setDescription(dog.getDescription());
	return dogForm;
    }

}
